package com.easy.sk.system.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.easy.common.bean.SeckillActivity;
import com.easy.common.service.ISeckillActivityService;
import com.easy.common.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@Component
public class SecKillScheduledTasks {
    @Autowired
    private ISeckillActivityService iSeckillActivityService;

    // 固定频率执行(上次开始后1分钟再次执行)
    @Scheduled(fixedRate = 1000*60)
    public void taskWithFixedRate() {
        System.out.println("taskWithFixedRate: " + System.currentTimeMillis());
        // 任务逻辑
        startActivity();
        endActivity();
    }

    // 固定延迟执行(上次完成后5秒再次执行)
    @Scheduled(fixedDelay = 5000)
    public void taskWithFixedDelay() {
        // 任务逻辑
    }

    // 使用Cron表达式(每天中午12点执行)
    @Scheduled(cron = "0 0 12 * * ?")
    public void taskWithCronExpression() {
        // 任务逻辑
    }


    public void endActivity(){
        UpdateWrapper<SeckillActivity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(SeckillActivity::getStatus, 2);
        //将活动状态还为1的,并且活动结束时间小于当前时间
        updateWrapper.lambda().eq(SeckillActivity::getStatus, 1).le(SeckillActivity::getEndTime, LocalDateTime.now());
        iSeckillActivityService.update(updateWrapper);
    }

    private void startActivity() {
        QueryWrapper<SeckillActivity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SeckillActivity::getStatus, 0);
        List<SeckillActivity> seckillActivities = iSeckillActivityService.list(queryWrapper);
        for (SeckillActivity seckillActivity : seckillActivities) {
            //三分钟内自动准备秒杀数据
            if (System.currentTimeMillis() > seckillActivity.getStartTime().atZone(ZoneId.systemDefault())
                    .toInstant()
                    .toEpochMilli() - SYS.SK_ACTIVITY_START_TIME) {
                try{
                    iSeckillActivityService.startPreheat(seckillActivity.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
